#include "Player.h"
#include <ctype.h>
#include <chrono>
#include <Windows.h>
using namespace std;

Player::Player(threadingInfo* th, int gridX, int gridY, int ID)
{
	this->threadInfo = th;
	xMax = gridX;
	yMax = gridY;
	pos posStruct1 = {rand() % gridX, rand() % gridY, ID, 0,0};
	posStruct = posStruct1;
}

int Player::getDirection(char c){
	c = toupper(c);
	int player = -1;
	for (int i = 0; i<2; i++){
		for (int j = 0; j < 4; j++){
			if (controlSets[i][j] == c){
				return j;
			}
		}
	}
	return 4;
}
void Player::updateStruct(int dir){
	switch(dir){
	//Is up
	case(0):
		if (posStruct.y > 0){
			posStruct.y--;
		}
		break;
	//Is left
	case(1):
		if (posStruct.x > 0){
			posStruct.x--;
		}
		break;
	//Is down
	case(2):
		if (posStruct.y < yMax){
			posStruct.y++;
		}
		break;

	//Is right
	case(3):
		if (posStruct.x < xMax){
			posStruct.x++;
		}
		break;
	default:
		break;
	}
		
}
void Player::operator() (){
	float fps_time = 1.0f/60.0f;
	chrono::high_resolution_clock timer;
	chrono::high_resolution_clock::time_point t = timer.now();
	while(1){
		threadInfo->mutex_kbd->lock();
		while (threadInfo->mutex_queue->empty()){
			threadInfo->mutex_kbd->unlock();
			threadInfo->mutex_kbd->lock();
		}
		
		prevX = posStruct.x;
		prevY = posStruct.y;
		while (!threadInfo->mutex_queue->empty()){
			char p = threadInfo->mutex_queue->front();
			threadInfo->mutex_queue->pop_front();
			int dir = getDirection(p);
			updateStruct(dir);
		}
		threadInfo->mutex_kbd->unlock();
		posStruct.fromX = prevX;
		posStruct.fromY = prevY;
		chrono::high_resolution_clock::time_point t2 = timer.now();
		chrono::duration<double> time_span = chrono::duration_cast<chrono::duration<double>>(t2-t);
		if (time_span.count() < fps_time){
			Sleep((fps_time - time_span.count()) * 1000);
		}
		t = timer.now();
		threadInfo->mutex_pos->lock();
		threadInfo->mutex_posUpdate->push_back(posStruct);
		threadInfo->mutex_pos->unlock();
	}
}

Player::~Player(void)
{
}
char Player::controlSets[2][4] = {{'W', 'A', 'S', 'D'}, {'I', 'J', 'K', 'L'}};
